<route lang="yaml">
meta:
enabled: false
</route>

<script setup lang="ts">
import type { Carousel } from '@/api/modules/carousel'
import type { FormInstance, FormRules } from 'element-plus'
import baiduApi from '@/api/modules/baiduTransApi'
import api from '@/api/modules/carousel'
import useSettingsStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'

// 百度翻译接口
const translateText = async (text: string, from: string, to: string): Promise<string> => {
  try {
    const response = await baiduApi.translate({
      query: text,
      from,
      to,
    })
    const data = response.data
    return data.trans_result[0].dst
  }
  catch (error) {
    console.error('Translation failed:', error)
    ElMessage.error('翻译失败，请稍后再试')
    return ''
  }
}
const translateToEnglish = async (text: string): Promise<string> => {
  return translateText(text, 'zh', 'en')
}

// 特殊字符检验
const validateNoSpecialChars = (value: string) => {
  // 禁用 # % & ? 这几个特殊字符
  return !/[#%&?]/.test(value)
}

const updateImg = ref(false)
const route = useRoute()
const router = useRouter()
const tabbar = useTabbar()
const settingsStore = useSettingsStore()
const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  carouselId: route.params.id as string | number ?? '',
  carouselUrl: '',
  carouselDescribe: '',
  carouselDescribeEn: '',
})

// 轮播图描述翻译
const translateDescriptionToEnglish = async () => {
  if (form.value.carouselDescribe && form.value.carouselDescribe.trim() !== '') {
    form.value.carouselDescribeEn = await translateToEnglish(form.value.carouselDescribe)
  }
}

const formRules = ref<FormRules>({
  carouselUrl: [
    { required: true, message: '请上传轮播图', trigger: 'change' },
  ],
  carouselDescribe: [
    { required: true, message: '请输入轮播图简介', trigger: 'blur' },
    { max: 200, message: '简介不能超过200个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (!validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  carouselDescribeEn: [
    { required: true, message: '请输入轮播图简介英文', trigger: 'blur' },
    { max: 2000, message: '英文简介不能超过2000个字符', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (/[\u4E00-\u9FA5]/.test(value)) {
          callback(new Error('英文简介不能包含中文'))
        }
        else if (!validateNoSpecialChars(value)) {
          callback(new Error('不能包含特殊字符'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
})

onMounted(() => {
})

function onSubmit() {
  return new Promise<void>(() => {
    formRef.value?.validate((valid) => {
      if (valid) {
        // 构造符合 School 接口的对象
        const carouselData: Carousel = {
          carouselId: Number(form.value.carouselId),
          carouselUrl: form.value.carouselUrl,
          carouselDescribe: form.value.carouselDescribe,
          carouselDescribeEn: form.value.carouselDescribeEn,
        }
        if (form.value.carouselId === '') {
          api.create(carouselData).then(() => {
            ElMessage.success({
              message: '新增成功',
            })
            goBack()
          })
        }
      }
    })
  })
}
function onCancel() {
  goBack()
}
// 返回列表页
function goBack() {
  if (settingsStore.settings.tabbar.enable && settingsStore.settings.tabbar.mergeTabsBy !== 'activeMenu') {
    tabbar.close({ name: 'list' })
  }
  else {
    router.push({ name: 'list' })
  }
}
async function handleLogoSuccess(file: any) {
  updateImg.value = true
  const formData = new FormData()
  formData.append('file', file.file)
  return await api.uploadAvatar(formData).then((res: any) => {
    updateImg.value = false
    if (res.code === 200) {
      form.value.carouselUrl = res.data
      ElMessage.success({
        message: '上传成功',
      })
    }
  })
}
</script>

<template>
  <div class="absolute size-full flex flex-col">
    <FaPageHeader :title="route.name === 'carouselCreate' ? '新增轮播图' : '编辑轮播图'" class="mb-0">
      <ElButton size="default" round @click="goBack">
        <template #icon>
          <FaIcon name="i-ep:arrow-left" />
        </template>
        返回
      </ElButton>
    </FaPageHeader>
    <ElForm ref="formRef" :model="form" :rules="formRules" label-width="130px" label-suffix="：" class="custom-form">
      <FaLayoutContainer right-side-width="500px" hide-right-side-toggle class="static" right-side-class="flex flex-col">
        <ElFormItem label="轮播图简介" prop="carouselDescribe">
          <ElInput v-model="form.carouselDescribe" placeholder="请输入轮播图简介">
            <template #append>
              <ElButton @click="translateDescriptionToEnglish">
                翻译
              </ElButton>
            </template>
          </ElInput>
        </ElFormItem>

        <ElFormItem label="轮播图英文简介" prop="carouselDescribeEn">
          <ElInput v-model="form.carouselDescribeEn" placeholder="请输入轮播图英文简介" />
        </ElFormItem>

        <ElFormItem label="上传轮播图" prop="carouselUrl">
          <ImageUpload v-model="form.carouselUrl" :loading="updateImg" action="" name="schoolLogo" :width="150" :height="150" :http-request="handleLogoSuccess" />
        </ElFormItem>

        <FaFixedActionBar>
          <ElButton type="primary" size="large" @click="onSubmit">
            提交
          </ElButton>
          <ElButton size="large" @click="onCancel">
            取消
          </ElButton>
        </FaFixedActionBar>
      </FaLayoutContainer>
    </ElForm>
  </div>
</template>

<style scoped>
.custom-form {
  display: flex;
  flex: 1;
  overflow: auto;
}
</style>
